package com.ponxu.mb.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ponxu.db.SqlBuilder;
import com.ponxu.db.SqlRunner;
import com.ponxu.db.wrap.RowWrapper;
import com.ponxu.mb.Global;
import com.ponxu.mb.db.ConnectionManager;
import com.ponxu.mb.model.Link;

/**
 * 友情链接
 * 
 * @author xwz
 * 
 */
public class LinkService {
	public static String LINK_TABLE = Global.read("DB_TABLE_PREFIX") + "link";

	// 友情链接状态
	public static final Map<String, String> LINK_STATUS = new HashMap<String, String>();
	static {
		LINK_STATUS.put("visible", "可见");
		LINK_STATUS.put("hidden", "私有");
	}

	// 全字段查询
	private static String fullCols = "*";
	private static RowWrapper<Link> fullRowWrapper = new RowWrapper<Link>() {
		public Link wrap(ResultSet rs) throws SQLException {
			Link link = new Link();
			link.setDescription(rs.getString("description"));
			link.setId(rs.getInt("id"));
			link.setName(rs.getString("name"));
			link.setStatus(rs.getString("status"));
			link.setTarget(rs.getString("target"));
			link.setUrl(rs.getString("url"));
			return link;
		}
	};

	public static List<Link> searchAll() {
		SqlBuilder.SELECT(fullCols);
		SqlBuilder.FROM(LINK_TABLE);
		return new SqlRunner(ConnectionManager.get()).select(SqlBuilder.SQL(),
				fullRowWrapper);
	}

	public static List<Link> searchVisible() {
		SqlBuilder.SELECT(fullCols);
		SqlBuilder.FROM(LINK_TABLE);
		SqlBuilder.WHERE("status='visible'");
		return new SqlRunner(ConnectionManager.get()).select(SqlBuilder.SQL(),
				fullRowWrapper);
	}

	public static Link getById(int id) {
		SqlBuilder.SELECT(fullCols);
		SqlBuilder.FROM(LINK_TABLE);
		SqlBuilder.WHERE("id=?");
		return new SqlRunner(ConnectionManager.get()).selectOne(
				SqlBuilder.SQL(), fullRowWrapper, id);
	}

	public static int add(Link link) {
		SqlBuilder.INSERT_INTO(LINK_TABLE);
		SqlBuilder.VALUES("name,description,url,target,status", "?,?,?,?,?");
		int id = new SqlRunner(ConnectionManager.get()).insert(
				SqlBuilder.SQL(), link.getName(), link.getDescription(),
				link.getUrl(), link.getTarget(), link.getStatus());
		link.setId(id);
		return id;
	}

	public static int update(Link link) {
		SqlBuilder.UPDATE(LINK_TABLE);
		SqlBuilder.SET("name=?,description=?,url=?,target=?,status=?");
		SqlBuilder.WHERE("id=?");
		return new SqlRunner(ConnectionManager.get()).execute(SqlBuilder.SQL(),
				link.getName(), link.getDescription(), link.getUrl(),
				link.getTarget(), link.getStatus(), link.getId());
	}

	public static int deleteById(int[] ids) {
		SqlBuilder.DELETE_FROM(LINK_TABLE);
		SqlBuilder.WHERE("id in " + SqlBuilder.inClause(ids));
		return new SqlRunner(ConnectionManager.get()).execute(SqlBuilder.SQL());
	}

}
